import { loadEnv, mergeConfig } from 'vite';
import baseConfig from './vite.config.base';
import './plugin/checkUpdate';
import configVisualizerPlugin from './plugin/visualizer';

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return mergeConfig(
    {
      mode: 'production',
      base: env.VITE_APP_BASE_URL,
      plugins: [...configVisualizerPlugin()],
      build: {
        minify: 'terser',
        rollupOptions: {
          output: {
            manualChunks(id) {
              try {
                if (id.includes('node_modules')) {
                  const name = id.split('node_modules/')[1].split('/');
                  if (name[0] === '.pnpm') {
                    return name[1];
                  } else {
                    return name[0];
                  }
                }
              } catch (error) {
                console.error(error);
              }
            },
            entryFileNames: 'js/[name].[hash].js',
            chunkFileNames: 'js/[name].[hash].js',
            assetFileNames(assetInfo) {
              if (assetInfo.name.endsWith('.css')) {
                return 'css/[name].[hash].css';
              }
              const imgs = ['.png', '.jpg', '.jpeg', '.svg'];
              if (imgs.some(ext => assetInfo.name.endsWith(ext))) {
                return 'imgs/[name].[hash].[ext]';
              }
              return 'assets/[name].[hash].[ext]';
            }
          }
        },
        terserOptions: {
          compress: {
            // drop_console: true,
            // 默认是true
            drop_debugger: true
          }
        },
        chunkSizeWarningLimit: 2000,
        sourcemap: false,
        reportCompressedSize: false
      }
    },
    baseConfig
  );
};
